<template>
  <div class="edit-box">
    <div class="inp-box">
      <div>计费方式</div>
      <el-select v-model="billingType" clearable>
        <el-option
          v-for="dict in dicts[DictDirection.重量模板计费方式]"
          :key="dict.id"
          :value="dict.dictValue"
          :label="dict.dictLabel"
        ></el-option>
      </el-select>
    </div>
    <div class="inp-box">
      <div>计费单重</div>
      <el-input v-model.number="batchWeight" type="text" clearable></el-input>
    </div>
    <div class="inp-box">
      <inp-val-format v-model:formatValue="batchValue" line-match-type="weight" placeholder="请输入分区名称"></inp-val-format>
    </div>
    <div class="btn-box">
      <el-button type="primary" :icon="CirclePlus" @click="batchAdd">批量新增</el-button>
      <el-button type="primary" :icon="EditPen" @click="batchEdit">批量修改</el-button>
    </div>
  </div>
  <div class="btns-box">
    <el-button type="primary" :icon="CirclePlus" @click="handleAdd">新增</el-button>
    <el-button type="primary" :icon="Edit" @click="handleUpdate">修改</el-button>
    <el-button
      type="danger"
      :icon="Delete"
      :loading="batchLoading"
      @click="batchDelete"
    >
      批量删除
    </el-button> 
  </div>
  <el-table
    v-loading="loading"
    :data="tableData"
    max-height="400px"
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" align="center"></el-table-column>
    <el-table-column label="区间名称" prop="name"></el-table-column>
    <el-table-column label="下限重量" prop="lowerWeight"></el-table-column>
    <el-table-column label="上线重量" prop="upperWeight"></el-table-column>
    <el-table-column label="计费方式" prop="billingType" :formatter="billingTypeFormatter"></el-table-column>
    <el-table-column label="计费单重" prop="billingSingleWeight"></el-table-column>
    <el-table-column label="排序" prop="orderBy"></el-table-column>
    <el-table-column label="操作" width="200">
      <template #default="{row,$index}">
        <el-button text type="primary" @click="handleEdit(row)">修改</el-button>
        <el-divider direction="vertical" class="divider-margin">
          <el-button
            text
            type="primary"
            @click="handleDelete(row,$index)"
          >
            删除    
          </el-button>
        </el-divider>
      </template>
    </el-table-column>
  </el-table>
  <!-- 新增重量模板 -->
  <el-dialog
    v-model="countryOpen"
    :title="titleCode"
    :close-on-click-modal="false"
    width="700px"
    append-to-body
  >
    <el-form
      ref="editFormRef"
      :rules="rules"
      :model="weightChangeForm"
      inline
      label-width="120px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="区间名称" prop="name" style="width: 82%;">
            <el-input v-model="weightChangeForm.name" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="下限重量" prop="lowerWeight">
            <el-input-number
              v-model="weightChangeForm.lowerWeight"
              :step="0.01"
              controls-position="right"
              clearable
            ></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="上限重量" prop="upperWeight">
            <el-input-number
              v-model="weightChangeForm.upperWeight"
              controls-position="right"
              :step="0.01"
              clearable
            ></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计费方式" prop="billingType" style="width: 82%;">
            <el-select
              v-model="weightChangeForm.billingType"
              filterable
              clearable
            >
              <el-option
                v-for="dict in dicts[DictDirection.重量模板计费方式]"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="计费单重" prop="billingSingleWeight">
            <el-input-number
              v-model="weightChangeForm.billingSingleWeight"
              :step="0.01"
              controls-position="right"
          
              clearable
            ></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序" prop="orderBy">
            <el-input-number
              v-model="weightChangeForm.orderBy"
              controls-position="right"
              clearable
            ></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div>
        <el-button type="primary" @click="editSave">确定</el-button>
        <el-button @click="editCancel">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import {
  ref,
  defineAsyncComponent,
  watchEffect,
} from 'vue'
import { EditPen, CirclePlus, Delete, Edit } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, ElButton } from 'element-plus'
import {
  addData,
  delData,
  getData,
  editData, getDetail } from '@/api/BusinessConfig/weightTemplate'
import useDicts, { DictDirection } from '@/store/modules/dicts'
import { validateForm } from '@/utils'

const InpValFormat = defineAsyncComponent(() => import('./InpValFormat.vue'))
const props = defineProps({
  basicInfo: {
    type: Object,
    default: () => ({}),
  },
})
const dicts = useDicts()
dicts.setDicts(DictDirection.重量模板计费方式)
// 批量操作
const loading = ref<boolean>(false)
const tableData = ref([])
const billingTypeFormatter = (row) => dicts.getDictLabel({ dict: DictDirection.重量模板计费方式, value: row.billingType })
/* 单个 新增编辑 --start */
const titleCode = ref(null)
const countryOpen = ref(false)
const weightChangeForm = ref({
  id: undefined,
  costPriceId: undefined,
  name: undefined,
  lowerWeight: undefined,
  upperWeight: undefined,
  billingType: undefined,
  billingSingleWeight: undefined,
  orderBy: undefined,
})
const editFormRef = ref(null)
const validatePass = (rules, value, callback) => {
  const val = Number(value)
  // eslint-disable-next-line no-restricted-globals
  if (isNaN(val)) {
    return callback('请输入数字')
  }
  return callback()
}
const ruleb = [{ required: true, message: '不能为空', trigger: ['blur', 'change'], validator: validatePass }]
const rulec = [{ required: true, message: '不能为空', trigger: 'blur' }]
const rules = {
  name: rulec,
  lowerWeight: ruleb,
  upperWeight: ruleb,
  billingType: ruleb,
  billingSingleWeight: ruleb,
}
const handleEdit = () => {
  countryOpen.value = true
}
const handleAdd = () => {
  countryOpen.value = true
  titleCode.value = '新增重量模板'
}
const editCancel = () => {
  countryOpen.value = false
}
// 新增重量模板
const editSave = () => {
  validateForm(editFormRef.value, async () => {
    let res = null
    weightChangeForm.value.costPriceId = props.basicInfo.id
    if (weightChangeForm.value.id != undefined) {
      res = await editData(weightChangeForm.value)
    } else {
      res = await addData(weightChangeForm.value)
    }
    ElMessage.success(res.msg)
    countryOpen.value = false
    getList()
  })
}
/* 单个 新增编辑 --end */
const getList = () => {
  if (!props.basicInfo.id) return
  const data = { pageNum: 1, pageSize: 10, costPriceId: props.basicInfo.id }
  getData(data).then(res => {
    if (res.code === 200) {
      tableData.value = res.data
    }
  })
}
/* 批量操作 */
const batchLoading = ref<boolean>()
const billingType = ref<string>()
const batchWeight = ref<number>()
const selectionList = ref([])
const ids = ref<any[]>([])
const single = ref<boolean>(true)
const multiple = ref<boolean>(true)
const batchValue = ref<any[]>([])
const handleDelete = (row, index) => {
  if (!row.id) {
    tableData.value.splice(index, 1)
  } else {
    ElMessageBox.confirm('该数据在系统内，是否继续删除?', '警告', {
      type: 'warning',
    }).then(() => {
      row.loading = true
      delData(row.id).then((res) => {
        if (res.code === 200) {
          ElMessage.success('删除成功')
          getList()
        } else {
          ElMessage.error('删除失败')
        }
      }).finally(() => {
        row.loading = false
      })
    })
  }
}
const checkBatch = () => {
  const errorLine = []
  batchValue.value.forEach((item, index) => {
    if (!item) errorLine.push(index)
  })
  if (errorLine.length) {
    ElMessage.error(`第${ errorLine.join(',') }行的模板有错误，请改正后重试`)
    return false
  }
  return true
}
const batchAdd = () => {
  if (checkBatch()) {
    const curUuid = uuid()
    tableData.value.unshift(...batchValue.value.map(item => {
      let name, lowerWeight, upperWeight
      if (Array.isArray(item)) {
        name = `${ item[0] }-${ item[1] }`
        lowerWeight = item[0]
        upperWeight = item[1]
      } else {
        name = item
        lowerWeight = 0
        upperWeight = item
      }
      return {
        name,
        lowerWeight,
        upperWeight,
        billingType: billingType.value,
        billingSingleWeight: batchWeight.value,
        planTypeId: '1',
        costPriceId: props.basicInfo.id,
        uuid: curUuid,
      }
    }))
  }
}
// 多选框选中数据
const handleSelectionChange = (rows: { [key: string]: any }[]) => {
  selectionList.value = rows
  const rowsList = JSON.parse(JSON.stringify(rows))
  ids.value = rowsList.map((item) => item.id)
  single.value = rowsList.length != 1
  multiple.value = !rowsList.length
}
const batchDelete = async () => {
  let isDelete = true
  if (selectionList.value.some(i => i.id)) {
    isDelete = await ElMessageBox.confirm('选中的数据包含系统数据,是否继续删除?', '警告', {
      type: 'warning',
    }).then(() => true).catch(() => false)
  }
  if (isDelete) {
    const unSaved = selectionList.value.filter(i => i.uuid).map(i => i.uuid)
    const saved = selectionList.value.filter(i => i.id).map(i => i.id)
    if (unSaved.length) {
      tableData.value = tableData.value.filter(i => !unSaved.includes(i.uuid))
    }
    if (saved.length) {
      batchLoading.value = true
      delData(saved.join(',')).then((res) => {
        if (res.code === 200) {
          ElMessage.success('删除成功！')
          getList()
        } else {
          ElMessage.error('删除失败！')
        }
      }).finally(() => {
        batchLoading.value = false
      })
    }
  }
}
const batchEdit = () => {
  if (checkBatch()) {
    if (batchValue.value.length > tableData.value.length) {
      // 超出处理
      batchValue.value.length = tableData.value.length
    }
    batchValue.value.forEach((item, index) => {
      let name, lowerWeight, upperWeight
      if (Array.isArray(item)) {
        name = `${ item[0] }-${ item[1] }`
        lowerWeight = item[0]
        upperWeight = item[1]
      } else {
        name = item
        lowerWeight = 0
        upperWeight = item
      }
      Object.assign(tableData.value[index], {
        name,
        lowerWeight,
        upperWeight,
      })
    })
  }
}
const save = () => addData(tableData.value).then((res) => {
  if (res.code === 200) {
    ElMessage.success('保存成功')
    getList()
  }
})

const handleUpdate = (row:{[key:string]:any}) => {
  const id = row.id || ids
  countryOpen.value = true
  titleCode.value = '修改重量模板'
  getDetail(id).then(res => {
    if (res.code === 200) {
      weightChangeForm.value = res.data
    }
  })
}
// 初始化
watchEffect(getList)
defineExpose({
  save,
})
</script>
<style>
.el-checkbox-group {
  display: block;
}
</style>
